import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home'
import store from '@/store'

const routes = [
  {
	  path:'/',
	  redirect:{
		  name:'home'
	  }
  },{
	  path:'/home',
	  name:'home',
	  meta:{
		  title:'首页'
	  },
	  component: ()=>import('@/views/Home')
  },{
	  path:'/category/:id',
	  name:'category',
	  meta:{
		  title:'图书分类'
	  },
	  // 路由懒加载 
	  component:()=>import('@/views/Books')
  },{
	  path:'/search',
	  name:'search',
	  meta:{
		  title:'搜索结果'
	  },
	  component:()=>import('@/views/Books')
  },{
	  path:'/newBooks',
	  name:'newBooks',
	  meta:{
		  title:'新书上市'
	  },
	  component:()=>import('@/components/Home/BooksNew')
  },{
	  path:'/book/:id',
	  name:'book',
	  meta:{
		  title:'图书'
	  },
	  component:()=>import('@/views/Book')
  },{
	  path:'/cart',
	  name:'cart',
	  meta:{
		  title:'购物车',
		  // requiresAuth:true
	  },
	  component:()=>import('@/views/ShoppingCart')
  },{
	  path:'/register',
	  name:'register',
	  meta:{
		  title:'注册'
	  },
	  component:()=>import('@/components/UserRegister')
  },{
	  path:'/login',
	  name:'login',
	  meta:{
		  title:'登陆'
	  },
	  component:()=>import('@/components/UserLogin')
  },{
	  path:'/check',
	  name:'check',
	  meta:{
		  title:'结算',
		  // 结算页面需要登陆权限
		  // requiresAuth:true
	  },
	  component:()=>import('@/views/Checkout')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 设置页面标题
router.afterEach((to)=>{
	document.title = to.meta.title
})

// 导航守卫
router.beforeEach(to=>{
	// 判断路由是否需要登陆权限
	if(to.matched.some(record=>record.meta.requiresAuth)){
		// 路由需要验证 判断用户是否已经登陆
		if(store.state.user.user){
			return true
		}else{
			return{
				path:'/login',
				query:{redirect:to.fullPath}
			}
		}
	}else{
		return true
	}
})

export default router
